/**
 * @file     finalPrices.js
 * @brief    [1475. 商品折扣后的最终价格](https://leetcode.cn/problems/final-prices-with-a-special-discount-in-a-shop/description/)
 * @author   Zhu
 * @date     2024-11-28 10:09
 */

/**
 * @param {number[]} prices
 * @return {number[]}
 */
var finalPrices = function (prices) {
    const n = prices.length;
    const ans = [];
    const stack = [];
    // 栈空时返回undefined
    const top = () => prices[stack[stack.length - 1]];
    // const empty = () => stack.length === 0;
    for (let i = 0; i < n; i++) {
        ans[i] = prices[i];
        //  val <= undefined 是 false, 所以可以不用额外判空
        while (/*!empty() && */ prices[i] <= top()) {
            // 确保栈顶是极大值
            const j = stack.pop();
            ans[j] = prices[j] - prices[i];
        }
        stack.push(i);
    }

    return ans;
};
